<!--用户管理页-->
<template>
  <div style="height: 6vh;background-color: #fff;padding: 10px 20px">
    <span style="font-size: 20px;line-height: 60px">车辆管理</span>
    <el-button type="primary" style="float: right;margin-top: 10px" @click="beforeAddVehicle">新建车辆</el-button>
  </div>
  <!-- 车辆搜索卡片 -->
  <el-card style="height: 70px;margin: 10px;">
    <el-form :inline="true">
      <el-form-item label="车辆品牌">
        <el-input placeholder="请输入内容" v-model="searchVehicleForm.brand" @keydown.enter="loadVehicle"></el-input>
      </el-form-item>
      <el-form-item label="车辆车牌">
        <el-input placeholder="请输入内容" v-model="searchVehicleForm.license" @keydown.enter="loadVehicle"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadVehicle">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!--  用户表格卡片-->
  <el-card style="margin: 10px;">
    <el-table :data="vehicleArr">
      <el-table-column label="编号" type="index" align="center" width="80"></el-table-column>
      <el-table-column label="车辆品牌" prop="brand" align="center"></el-table-column>
      <el-table-column label="车辆号" prop="license" align="center"></el-table-column>
      <el-table-column label="车辆识别码" prop="code" align="center"></el-table-column>
      <el-table-column label="车辆类型" prop="type" align="center">
        <template #default="scope">
          {{ getType(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="购买价格" prop="price" align="center"></el-table-column>
      <el-table-column label="购买时间" prop="buyTime" align="center"></el-table-column>
      <el-table-column label="上牌时间" prop="regTime" align="center"></el-table-column>
      <el-table-column label="电池类型" prop="batteryType" align="center">
        <template #default="scope">
          {{ getBatteryLabel(scope.row.batteryType) }}
        </template>
      </el-table-column>
      <el-table-column label="车辆状态" prop="status" align="center">
        <template #default="scope">
          {{ getStatus(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editVehicle(scope.row.id)" link>编辑</el-button>
          <el-button type="danger" size="small" link @click="delVehicle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <el-dialog :title="dialogTitle" v-model="dialogVisible" style="width:1000px;padding:40px;">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="车辆品牌">
            <el-input placeholder="请输入内容" v-model="saveVehicleForm.brand"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车辆牌号">
            <el-input placeholder="请输入内容" v-model="saveVehicleForm.license"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="车辆型号">
            <el-input placeholder="请输入内容" v-model="saveVehicleForm.model"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车辆识别码" >
            <el-input placeholder="请输入内容" v-model="saveVehicleForm.code"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="车辆排量">
            <el-select placeholder="请选择" v-model="saveVehicleForm.displacement">
              <el-option label="1.6" value="1"></el-option>
              <el-option label="2.5" value="2"></el-option>
              <el-option label="4" value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车辆类型">
            <el-select placeholder="请选择" v-model="saveVehicleForm.type">
              <el-option label="轿车" value="10"></el-option>
              <el-option label="客车" value="20"></el-option>
              <el-option label="货车" value="30"></el-option>
              <el-option label="挂车" value="40"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="车身颜色">
            <el-select placeholder="请选择" v-model="saveVehicleForm.color">
              <el-option label="黑" value="10"></el-option>
              <el-option label="白" value="20"></el-option>
              <el-option label="蓝" value="30"></el-option>
              <el-option label="灰" value="40"></el-option>
              <el-option label="银" value="50"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="里程数">
            <el-input placeholder="请输入内容" v-model="saveVehicleForm.kilometers"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="购买时间">
            <el-date-picker type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            v-model="saveVehicleForm.buyTime" @change="validateDate"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上牌时间">
            <el-date-picker type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            v-model="saveVehicleForm.regTime" @change="validateDate"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="购买价格">
            <el-input placeholder="请输入内容" v-model="saveVehicleForm.price"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电池类型">
            <el-select placeholder="请选择" v-model="saveVehicleForm.batteryType">
              <el-option v-for="item in batteryTypeArr" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="saveVehicle">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref } from "vue";
import qs from "qs";
import axios from "axios";
import { ElMessage } from "element-plus";

// 存储车辆列表数据
const vehicleArr = ref([]);

// 搜索表单的数据模型
const searchVehicleForm = ref({ brand: '', license: '' });

// 加载车辆数据的方法（调用后端接口）
const loadVehicle = () => {
  let data = qs.stringify(searchVehicleForm.value);
  console.log(data);
  axios.get(BASE_URL + '/v1/vehicle/select?' + data)
    .then((response) => {
      if (response.data.code === 2000) {
        vehicleArr.value = response.data.data;
        console.log(vehicleArr.value);
      } else {
        ElMessage.error('未查询到数据');
      }
    });
};

// 页面加载完成后自动执行 loadVehicle
onMounted(() => {
  loadVehicle();
});

// 重置搜索表单并重新加载数据
const resetSearch = () => {
  searchVehicleForm.value = { brand: '', license: '' };
  loadVehicle();
};

// 控制弹窗是否可见
const dialogVisible = ref(false);

// 表单数据模型，用于新增或编辑车辆
const saveVehicleForm = ref({
  id: '',
  brand: '',
  license: '',
  model: '',
  code: '',
  displacement: '',
  kilometers:'',
  status: '',
  type: '',
  color: '',
  regTime: '',
  buyTime: '',
  price: '',
  batteryType: ''
});

// 电池类型选项列表
const batteryTypeArr = ref([]);
onMounted(() => {
  loadDictOption(batteryTypeArr,'BATTERY_TYPE');
})

// 车辆状态选项列表
const statusCode = ref([
  { label: '空闲', value: '1' },
  { label: '占用', value: '2' }
]);

// 车辆类型选项列表
const vehicleType = ref([]);
onMounted(() => {
  loadDictOption(vehicleType,'VEHICLE_TYPE');
})

// 根据 value 获取车辆类型的 label
const getType = (value) => {
  const item = vehicleType.value.find(i => i.value === value);
  return item ? item.label : '未知类型';
};

// 根据 value 获取车辆状态的 label
const getStatus = (value) => {
  const item = statusCode.value.find(i => i.value === value);
  return item ? item.label : '未知状态';
};

// 根据 value 获取电池类型的 label
const getBatteryLabel = (value) => {
  const item = batteryTypeArr.value.find(i => i.value === value);
  return item ? item.label : '未知类型';
};

// 保存车辆信息方法
const saveVehicle = () => {
  if (!saveVehicleForm.value.license || saveVehicleForm.value.license.trim()===''){
    ElMessage.error('请输入车牌号！');
    return;
  }
  if (!saveVehicleForm.value.brand || saveVehicleForm.value.brand.trim()===''){
    ElMessage.error('请输入车辆品牌！');
    return;
  }
  axios.post(BASE_URL + '/v1/vehicle/save', qs.stringify(saveVehicleForm.value))
      .then((response)=>{
        if (response.data.code === 2000){
          ElMessage.success('保存成功！');
          dialogVisible.value=false;
          loadVehicle();
        }else if(response.data.code === 3001){
          ElMessage.error(response.data.data);//显示具体错误信息
        }else {
          ElMessage.error(response.data.message);//打印错误信息
        }
      })
};

// 关闭弹窗时提示用户确认，并清空表单
const closeDialog = () => {
  if (confirm('您确认关闭吗？')) {
    dialogVisible.value = false;
    saveVehicleForm.value = {};
  }
};

// 弹窗标题
const dialogTitle = ref('新建车辆');

// 编辑车辆方法（打开弹窗并设置标题）
const editVehicle = (id) => {
  dialogTitle.value = '编辑车辆';
  dialogVisible.value = true;
  axios.get(BASE_URL + '/v1/vehicle/select?id=' + id).then((response)=>{
    if (response.data.code === 2000){
      console.log(id)
      saveVehicleForm.value = response.data.data[0];
      saveVehicleForm.value.type = getType(saveVehicleForm.value.type);
      saveVehicleForm.value.status = getStatus(saveVehicleForm.value.status);
    }else {
      ElMessage.error(response.data.message);
    }
  })
};

// 新增车辆方法（打开弹窗并设置标题）
const beforeAddVehicle = () => {
  dialogTitle.value = '新建车辆';
  dialogVisible.value = true;
};
// 删除车辆
const delVehicle =(id)=>{
  if (confirm('确定删除吗？')) {
    axios.post(BASE_URL + '/v1/vehicle/delete/' + id).then((response) => {
      if (response.data.code === 2000) {
        ElMessage.success('删除成功！');
        loadVehicle();
      } else {
        ElMessage.error(response.data.message);
      }
    })
  }
}

const validateDate = ()=>{
  const buyTime = new Date(saveVehicleForm.value.buyTime);
  const regTime = new Date(saveVehicleForm.value.regTime);
  if (buyTime && regTime && buyTime >= regTime){
    ElMessage.error('购买时间不能早于上牌时间！');
    saveVehicleForm.value.regTime='';
  }
}
</script>


<style scoped>

</style>